﻿using System;
using SLNGP.Common.Extensions;
using SLNGP.Core.Run;

namespace SLNGP.Core.Genes
{
    public class VariableGene<T> : Gene
    {
        private string _name;
        public VariableGene(string name)
        {
            _name = name;
        }

        public override object Execute(IGeneticProgrammingRun run)
        {
            if (!run.Variables.ContainsKey(_name))
                throw new GeneticProgrammingException("Gene exceution failure. Could not find variable with name: " + _name);

            if (!run.Variables[_name].Is(typeof(T)))
                throw new GeneticProgrammingException(string.Format("Gene execution failure. Variable {0} is not of type {1}", _name, typeof(T).FullName));

            return (T)run.Variables[_name];
        }

        public override string GetStringDisplay()
        {
            return _name;
        }

        public override Type GeneReturnType
        {
            get { return typeof (T); }
        }
    }
}